<template>
  <div class="app-container" style="width: 100%">
    <el-row>
      <el-col
        class="search-container"
        :span="6"
        :offset="1"
        style="height: 420px"
      >
        <el-form :model="searchParam" :inline="true" label-width="100px">
          <el-form-item label="物料号">
            <el-input
              v-model="searchParam.materialCode"
              placeholder="请选择物料号"
              clearable
            >
              <template #append>
                <el-button type="success" plain @click="showWorkOrderSelect"
                  >选择</el-button
                >
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="供应商">
            <el-input
              v-model="searchParam.partnerCode"
              placeholder="请选择供应商"
              clearable
            >
              <template #append>
                <el-button type="success" plain @click="showWorkOrderSelect2"
                  >选择</el-button
                >
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="批次">
            <el-input
              v-model="searchParam.batch"
              placeholder="请输入批次(6位)"
              clearable
              @change="batchChange"
            />
          </el-form-item>
          <el-form-item label="流水号1">
            <el-input
              v-model="searchParam.serial1"
              placeholder="请输入流水号"
              clearable
            />
          </el-form-item>
          <el-form-item label="流水号2">
            <el-input
              v-model="searchParam.serial2"
              placeholder="请输入流水号"
              clearable
            />
          </el-form-item>
          <el-form-item label="流水号3">
            <el-input
              v-model="searchParam.serial3"
              placeholder="请输入流水号"
              clearable
            />
          </el-form-item>
          <el-form-item style="width: 70%; margin-left: 10%">
            <el-button type="primary" @click="getBarCode" style="width: 100%"
              >预览</el-button
            >
          </el-form-item>

          <!-- <el-form-item label="打印机">
            <el-select
              v-model="searchParam.printer"
              clearable
              placeholder="请选打印机"
              style="width: 250px"
            >
              <el-option
                v-for="item in printers"
                :key="item.printerName"
                :label="item.printerName"
                :value="item.printerName"
              />
            </el-select>
          </el-form-item> -->

          <el-form-item style="width: 70%; margin-left: 10%">
            <el-button
              type="primary"
              @click="printFun"
              style="width: 100%"
              :disabled="isPrint"
              >打印</el-button
            >
          </el-form-item>
        </el-form>
      </el-col>
      <el-col
        class="search-container"
        :span="13"
        :offset="2"
        style="height: 600px; padding-top: 60px"
        border="1"
        id="printId"
      >
        <table align="center" width="80%" cellspacing="0">
          <tr>
            <td>物料号</td>
            <td>{{ searchParam.materialCode }}</td>
            <td>物料描述</td>
            <td>{{ searchParam.materialName }}</td>
          </tr>
          <tr>
            <td>供应商代码</td>
            <td>{{ searchParam.partnerCode }}</td>
            <td>供应商</td>
            <td>{{ searchParam.partnerName }}</td>
          </tr>
          <tr>
            <td>批次</td>
            <td>{{ searchParam.batch }}</td>
            <td colspan="2" rowspan="4" id="showQrP">
              <canvas id="showQr"></canvas>
            </td>
          </tr>
          <tr>
            <td>流水号1</td>
            <td>{{ searchParam.serial1 }}</td>
          </tr>
          <tr>
            <td>流水号2</td>
            <td>{{ searchParam.serial2 }}</td>
          </tr>
          <tr>
            <td>流水号3</td>
            <td>{{ searchParam.serial3 }}</td>
          </tr>
          <tr style="height: 65px">
            <td colspan="4" style="height: 45px">
              {{ pCode }}
            </td>
          </tr>
        </table>
      </el-col>
    </el-row>
    <wms-conten-select
      :visible="selectDialogSELECT.visible"
      @change-visible="changeVisibleSELECT"
      :brekList="brekList"
    />
    <wms-partner-select
      :visible="selectDialogSELECT2.visible"
      @change-visible="changeVisibleSELECT2"
      :brekList="brekList2"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
import QRCode from "qrcode";
import defaultSettings from "@/settings";
import { useRoute, useRouter } from "vue-router";
import { getLodop } from "@/utils/LodopFuncs";
const dictionaryStore = useDictStoreHook();
let isPrint = ref(true);

defineOptions({
  name: "WMSLABELPRINTING",
  inheritAttrs: false,
});

// 初始化搜索参数数据
let searchParam = reactive({
  partnerId: "",
  partnerCode: "",
  partnerName: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  poSa: "",
  poSaItem: "",
  batch: YYMMDD(),
  serial1: "000001",
  serial2: "",
  serial3: "",
  number: 1,
  printer: "",
});
let pCode = ref();
onMounted(() => {
  getPartner();
  getMaterial();
  getPrinterl();
});

function YYMMDD() {
  var myDate = new Date();
  var month = myDate.getMonth() + 1;
  var Day = myDate.getDate();
  var today = "";
  if (month < 10) {
    if (Day < 10) {
      today =
        myDate.getFullYear().toString().slice(-2) + "0" + month + "0" + Day;
    } else {
      today = myDate.getFullYear().toString().slice(-2) + "0" + month + Day;
    }
  } else {
    if (Day < 10) {
      today = myDate.getFullYear().toString().slice(-2) + month + "0" + Day;
    } else {
      today = myDate.getFullYear().toString().slice(-2) + month + Day + "";
    }
  }
  return today;
}
// 获取打印数据
async function getBarCode() {
  if (!searchParam.materialCode) {
    ElMessage.error("物料号不可为空");
    return;
  }
  if (!searchParam.partnerCode) {
    ElMessage.error("供应商不可为空");
    return;
  }
  if (!searchParam.batch || searchParam.batch.length != 6) {
    ElMessage.error("批次必须为6位");
    return;
  }
  if (!searchParam.serial1 || searchParam.serial1.length != 6) {
    ElMessage.error("流水号必须为6位");
    return;
  }
  pCode.value = `Mt${searchParam.materialCode}`;
  if (searchParam.partnerCode) {
    pCode.value += `-Pt${searchParam.partnerCode}`;
  }
  pCode.value += `-Sb${searchParam.batch}`;
  pCode.value += `-Na${searchParam.serial1}`;
  if (searchParam.serial2) {
    pCode.value += `-Nb${searchParam.serial2}`;
  }
  if (searchParam.serial3) {
    pCode.value += `-Nc${searchParam.serial3}`;
  }
  const datam = await request({
    url: `/wms/mdmmaterial/queryByCode`,
    method: "post",
    data: { materialCode: searchParam.materialCode },
  }).finally(() => {});
  if (datam.code == 200 && datam.data) {
    searchParam.materialName = datam.data.materialName;
  } else {
    ElMessage.error("物料号对应物料未维护");
  }
  const datap = await request({
    url: `/wms/mdmpartner/queryByCode`,
    method: "post",
    data: { partnerCode: searchParam.partnerCode },
  }).finally(() => {});
  if (datap.code == 200 && datap.data) {
    searchParam.partnerName = datap.data.partnerName;
  } else {
    ElMessage.error("供应商号对应供应商未维护");
  }
  if (datam.code == 200 && datap.code == 200 && datam.data && datap.data) {
    isPrint.value = false;
    QRCode.toCanvas(document.getElementById("showQr"), pCode.value, {
      width: 230, // 可以根据需要调整二维码的大小
      margin: 1, // 可以根据需要调整二维码的边距
    });
  }
}

//工作任务选择弹窗显隐
const selectDialogSELECT2 = ref({
  visible: false,
});
const changeVisibleSELECT2 = (val: boolean, data: any) => {
  selectDialogSELECT2.value.visible = val;
  if (data) {
    console.log("选择的数据", data);
    searchParam.partnerId = data.partnerId;
    searchParam.partnerName = data.partnerName;
    searchParam.partnerCode = data.partnerCode;
  }
};

const brekList2 = ref([]);
const showWorkOrderSelect2 = () => {
  console.log("showWorkOrderSelect2");
  selectDialogSELECT2.value.visible = true;
  // if (formData.mesWorkOrderPlanId != "") {
  //   brekList2.value.push(formData);
  // }
};

//工作任务选择弹窗显隐
const selectDialogSELECT = ref({
  visible: false,
});
const changeVisibleSELECT = (val: boolean, data: any) => {
  selectDialogSELECT.value.visible = val;
  if (data) {
    console.log("选择的数据", data);
    searchParam.materialId = data.materialId;
    searchParam.materialName = data.materialName;
    searchParam.materialCode = data.materialCode;
  }
};

const brekList = ref([]);
const showWorkOrderSelect = () => {
  console.log("showWorkOrderSelect");
  selectDialogSELECT.value.visible = true;
  // if (formData.mesWorkOrderPlanId != "") {
  //   brekList.value.push(formData);
  // }
};

// 打印模板全用div和span等原生html书写（确保打印格式不变）
// 样式全用行内style书写（确保样式生效）

const route = useRoute();
function printFun(pitem: RootObject) {
  let LODOP = getLodop();
  LODOP.SET_PRINTER_INDEX(searchParam.printer);
  LODOP.PRINT_INIT(`打印-${pCode.value}`);
  LODOP.SET_LICENSES(
    defaultSettings.printCompany,
    defaultSettings.printLicenses,
    "",
    ""
  );
  LODOP.SET_PRINT_STYLE("Bold", 1);
  LODOP.SET_PRINT_STYLE("FontSize", 9);
  LODOP.SET_PRINT_STYLE("Stretch");
  LODOP.SET_PRINT_STYLE("FontName", "cursive"); // 需要服务端机器安装同样字体，才能生效
  LODOP.SET_PRINT_PAGESIZE(1, 9500, 580, ""); // 设置纸张类型（方向、宽度、高度、纸张类型名称）
  LODOP.ADD_PRINT_LINE("14%", 0, "14%", "100%", 0, 1);
  LODOP.ADD_PRINT_LINE("30%", 0, "30%", "100%", 0, 1);
  LODOP.ADD_PRINT_LINE("48%", 0, "48%", "45%", 0, 1);
  LODOP.ADD_PRINT_LINE("63%", 0, "63%", "45%", 0, 1);
  LODOP.ADD_PRINT_LINE("78%", 0, "78%", "45%", 0, 1);
  LODOP.ADD_PRINT_LINE("92%", 0, "92%", "45%", 0, 1);
  LODOP.ADD_PRINT_LINE(0, "25%", "92%", "25%", 0, 1);
  LODOP.ADD_PRINT_LINE(0, "45%", "92%", "45%", 0, 1);
  LODOP.ADD_PRINT_LINE(0, "60%", "30%", "60%", 0, 1);
  LODOP.ADD_PRINT_TEXT("5%", "10%", "23%", "15%", "物料号"); //边框设置：上、左、宽、高
  LODOP.ADD_PRINT_TEXT("5%", "27%", "25%", "15%", searchParam.materialCode); //边框设置：上、左、宽、高
  LODOP.ADD_PRINT_TEXT("5%", "46%", "25%", "15%", "物料描述"); //边框设置：上、左、宽、高
  LODOP.ADD_PRINT_TEXT("20%", "10%", "23%", "15%", "供应商码"); //边框设置：上、左、宽、高
  LODOP.ADD_PRINT_TEXT("20%", "27%", "25%", "15%", searchParam.partnerCode); //边框设置：上、左、宽、高
  LODOP.ADD_PRINT_TEXT("20%", "46%", "25%", "15%", "供应商"); //边框设置：上、左、宽、高
  LODOP.ADD_PRINT_TEXT("35%", "10%", "23%", "15%", "PO/SA"); //边框设置：上、左、宽、高
  LODOP.ADD_PRINT_TEXT(
    "33%",
    "27%",
    "20%",
    "15%",
    searchParam.poSa + " / " + searchParam.poSaItem
  ); //边框设置：上、左、宽、高
  LODOP.ADD_PRINT_TEXT("54%", "10%", "23%", "15%", "批次"); //边框设置：上、左、宽、高
  LODOP.ADD_PRINT_TEXT("54%", "27%", "25%", "15%", searchParam.batch); //边框设置：上、左、宽、高
  LODOP.ADD_PRINT_TEXT("69%", "10%", "23%", "15%", "流水号"); //边框设置：上、左、宽、高
  LODOP.ADD_PRINT_TEXT("69%", "27%", "25%", "15%", searchParam.serial); //边框设置：上、左、宽、高
  LODOP.ADD_PRINT_TEXT("84%", "10%", "23%", "15%", "数量"); //边框设置：上、左、宽、高
  LODOP.ADD_PRINT_TEXT("84%", "27%", "25%", "15%", searchParam.number); //边框设置：上、左、宽、高

  LODOP.SET_PRINT_STYLE("FontSize", 7);
  LODOP.ADD_PRINT_TEXT("3%", "61%", "33%", "15%", searchParam.materialName); //边框设置：上、左、宽、高 ---物料描述
  LODOP.ADD_PRINT_TEXT("17%", "61%", "31%", "15%", searchParam.partnerName); //边框设置：上、左、宽、高 ---供应商

  LODOP.SET_PRINT_STYLE("FontSize", 8);
  LODOP.ADD_PRINT_TEXT("93%", "12%", "100%", "6%", pCode.value); //边框设置：上、左、宽、高
  LODOP.ADD_PRINT_BARCODE("35%", "55%", "25%", "25%", "QRCode", pCode.value);
  // LODOP.ADD_PRINT_HTM(
  //   10,
  //   10,
  //   300,
  //   300,
  //   document.getElementById(`printId`)?.innerHTML
  // );
  LODOP.NEWPAGE(); //另起一页
  LODOP.PREVIEW();
  //LODOP.PRINT(); // 打印

  setTimeout(() => {
    setSerial();
    getBarCode();
  }, 1000);
}

let printers = ref([]);
async function getPrinterl() {
  const data = await request({
    url: "/system/sysprintersetting/getList",
    method: "post",
    data: {},
  });
  printers.value = data.data;
}

async function getSerial() {
  const data = await request({
    url: "/wms/srmasn/getSerial",
    method: "post",
    data: searchParam,
  });
  searchParam.serial = data.data;
}
async function setSerial() {
  const data = await request({
    url: "/wms/srmasn/setSerial",
    method: "post",
    data: searchParam,
  });
  searchParam.serial = data.data;
}

let partners = ref([]);
async function getPartner() {
  const data = await request({
    url: "/wms/mdmpartner/getList",
    method: "get",
  });
  partners.value = data.data;
}
function partnerChange(id: string) {
  if (id) {
    var partner = partners.value.find((item) => {
      return item.id === searchParam.partnerId;
    });
    searchParam.partnerCode = partner.partnerCode;
    searchParam.partnerName = partner.partnerName;
    getPosa();
    getSerial();
    //qrCodeShow();
  }
}

function batchChange() {
  getSerial();
}

let materials = ref([]);
async function getMaterial() {
  const data = await request({
    url: "/wms/mdmmaterial/getList",
    method: "get",
  });
  materials.value = data.data;
}
function materialChange(id: string) {
  if (id) {
    var material = materials.value.find((item) => {
      return item.id === searchParam.materialId;
    });
    searchParam.materialCode = material.materialCode;
    searchParam.materialName = material.materialName;
  }
  getPosa();
  getSerial();
  //qrCodeShow();
}
async function getPosa() {
  if (searchParam.materialId && searchParam.partnerId) {
    const data = await request({
      url:
        "/wms/mdmpartnermaterial/getOne/" +
        searchParam.partnerId +
        "/" +
        searchParam.materialId,
      method: "get",
    });
    if (data.code == 200) {
      searchParam.poSa = data.data.poSa;
      searchParam.poSaItem = data.data.poSaItem;
    }
  }
}
async function qrCodeShow() {
  if (
    searchParam.materialId &&
    searchParam.materialCode &&
    searchParam.posa &&
    searchParam.batch &&
    searchParam.number
  ) {
    const qrCodeElement = document.getElementById("showQr");
    console.log("二维码打印！！");
    console.log(
      searchParam.materialId +
        searchParam.materialCode +
        searchParam.posa +
        searchParam.batch +
        searchParam.number
    );
    if (qrCodeElement) {
      try {
        await QRCode.toCanvas(
          qrCodeElement,
          searchParam.materialId +
            searchParam.materialCode +
            searchParam.posa +
            searchParam.batch +
            searchParam.number,
          {
            width: 100, // 可以根据需要调整二维码的大小
            margin: 1, // 可以根据需要调整二维码的边距
          }
        );
      } catch (err) {
        console.error("Error generating QR code:", err);
      }
    }
  }
}
</script>
<style scoped>
table {
  border-right: 1px solid #0000001f;
  border-bottom: 1px solid #0000001f;
  text-align: center;
}

table td {
  height: 70px;
  border-left: 1px solid #0000001f;
  border-top: 1px solid #0000001f;
  width: 25%;
}
</style>
